package ktv;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @Author admin
 * @Date 2019/4/3 8:15
 * 工具类，实现相关功能/操作
 */
public class SongDaoImp implements SongDao {
    ArrayList<Song> arrayList = new ArrayList<Song>();
/*初始化列表*/
    @Override
    public void init() {
        Song song1 = new Song("小青蛙");
        Song song2 = new Song("小蛤蟆");
        Song song3 = new Song("小蝌蚪");
        Song song4 = new Song("大青蛙");
        Song song5 = new Song("大蛤蟆");
        arrayList.add(song1);
        arrayList.add(song2);
        arrayList.add(song3);
        arrayList.add(song4);
        arrayList.add(song5);
    }

    @Override
    public void add(Song song) {
        arrayList.add(song);
        System.out.println("已添加歌曲："+song.getName());
    }

    @Override
    public void all() {
        System.out.println("初始化歌曲列表：");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()){
            Song song = (Song) iterator.next();
            System.out.print(song.getName()+"\t");
        }
        System.out.println();

    }

    @Override
    public void top(String name) {
        /*调用方法完成判断是否存在该歌曲*/
        Song song = select(name);
        if (song==null){
            System.out.println("当前列表中没有此歌曲");
        }else{
            /*完成置顶操作：
            * 1）找到歌曲名对应的歌曲对象
            * 2）列表中删除该对象
            * 3）将该对象添加到列表的第一项*/
            arrayList.remove(song);
            arrayList.add(0,song);
            System.out.println("已将歌曲"+song.getName()+"置顶");
        }
    }

    @Override
    public void before(Song music) {
        /*找到歌曲的下标*/
        int index=arrayList.indexOf(music);
        /*前移：  一种方法：先删除，再添加
        *         另一种方法：用set返回完成替换操作*/
        arrayList.remove(music);
        arrayList.add(index-1,music);
    }

    @Override
    public Song select(String name) {
        for (int i=0;i<arrayList.size();i++){
            if (arrayList.get(i).getName().equals(name)){
                return arrayList.get(i);
            }
        }
        return null;
    }
}
